#!/bin/bash

if [ $# -ne 2 ]; then
  echo "paras num should be cpubench zipfile with path, such as:"
  echo "    ./$0 <type> /home/test/CPUBench-v1.1.1.tar.gz"
  echo "paras:"
  echo "    <type> should be one of ts_server/ts_desktop/server/desktop/laptop"
  exit
fi

type=$1
cpubenchtar=$2
echo "para1st=<$type>, para2nd=<$cpubenchtar>, paranum=$#"

if [ "$type" == "ts_server" ]; then
  deletelist="standbytimej cppperf ssoftwarej redis endurance nginx x264 glperfbench spark mysql"
elif [ "$type" == "ts_desktop" ]; then
  deletelist="cppperf redis nginx x264 spark mysql"
elif [ "$type" == "server" ]; then
  deletelist="standbytimej cppperf ssoftwarej redis endurance nginx x264 glperfbench spark mysql"
elif [ "$type" == "desktop" ]; then
  deletelist="cppperf redis nginx x264 spark mysql videodecode"
elif [ "$type" == "laptop" ]; then
  deletelist="cppperf redis nginx x264 spark mysql videodecode"
else
  echo "type<$type> is incorrect"
  exit
fi

#---------------------------------------
datetim=$(date +"%Y%m%d-%H%M%S")
curdir=$(cd "$(dirname "$0")"; pwd)
topdir=$(cd "$(dirname "${curdir}/../../../../}")"; pwd)
srcdir=$(cd "$(dirname "${curdir}/../../../}")"; pwd)
dstname="GCBSv3-${type}-${datetim}"
dstdir="${topdir}/${dstname}"
wklddir="${dstdir}/workload"
cpubenchdir="${wklddir}/cpubenchplus"
tmpdir="${wklddir}/tmp"
md5file="${topdir}/${dstname}.md5sum"

echo "curdir=$curdir"
echo "topdir=$topdir"
echo "srcdir=$srcdir"
echo "dstdir=$dstdir"

function backup_gcbs() {
  cp -r "${srcdir}" "${dstdir}"

  for dir in ${deletelist[@]}
  do
    echo "--$dir"
    mkdir -p ${tmpdir}/${dir}
    cp ${wklddir}/${dir}/*py ${tmpdir}/${dir}
    rm -rf "${wklddir}/${dir}"
    mv ${tmpdir}/${dir} "${wklddir}/"
  done

  rm -rf "${tmpdir}"
  rm -rf "${dstdir}/.git/"
}

function backup_cpubench() {
  tar zxf ${cpubenchtar} -C ${cpubenchdir}
  mv "${cpubenchdir}/CPUBench/"* "${cpubenchdir}/src"
  rm -rf "${cpubenchdir}/CPUBench/"
  rm -rf "${cpubenchdir}/src/external/"
}

function git_gcbs() {
  git branch --show-current >> "${dstdir}/docs/readme-version.txt"
  git log -1 >> "${dstdir}/docs/readme-version.txt"

  cd ${dstdir}
  git init
  git add .
  git commit -sm "init: GCBS-server-ts"
  cd ${topdir}
}

function git_info() {
  cd ${srcdir}
  gitbr=$(git branch | grep "\*")
  gitcommit=$(git log -1 | head -1)
  echo "branch ${gitbr}" >> "${md5file}"
  echo "${gitcommit}" >> "${md5file}"
}

backup_gcbs
backup_cpubench
git_info
#git_gcbs

#cd ${topdir}/${dstname}/docs/utils/verify
#python3 init_verification.py
#sha256sum verification.txt > checksum.sha

cd ${topdir}
echo "curpwd=$(pwd)"
echo "tar -jcvf ${dstname}.tar.bz2 ${dstname}"
tar -jcf "${dstname}.tar.bz2" "${dstname}"
du -sh "${dstdir}"
ls -lh "${dstname}.tar.bz2"
md5val=$(md5sum "${dstname}.tar.bz2")

echo "${md5val}" >> "${md5file}"
cat "${md5file}"

